import { defineStore } from 'pinia';
import { ref, watch } from 'vue';

export const useAccessibilityStore = defineStore('accessibility', () => {
  // --- State ---
  // 从 localStorage 初始化状态，若不存在则默认为 false
  const isEnabled = ref(JSON.parse(localStorage.getItem('accessibilityEnabled') || 'false'));

  // --- Actions ---
  /**
   * 切换无障碍模式的开关状态
   */
  function toggle() {
    isEnabled.value = !isEnabled.value;
  }

  // --- Watcher ---
  // 监听 isEnabled 状态的变化，并执行副作用
  watch(isEnabled, (newValue) => {
    // 将新状态存入 localStorage
    localStorage.setItem('accessibilityEnabled', JSON.stringify(newValue));

    // 根据状态为 <html> 根元素添加或移除 CSS 类
    const root = document.documentElement;
    if (newValue) {
      root.classList.add('accessibility-mode');
    } else {
      root.classList.remove('accessibility-mode');
    }
  }, { immediate: true }); // immediate: true 确保在 store 初始化时就立即执行一次

  return { isEnabled, toggle };
});